package com.have.blog.xo.service.admin.impl;

import com.github.pagehelper.PageHelper;


import com.have.blog.base.enums.BlogPublishStatus;
import com.have.blog.base.enums.BlogStatus;
import com.have.blog.commons.service.RedisService;
import com.have.blog.model.api.CommonPage;
import com.have.blog.model.mapper.TBlogMapper;
import com.have.blog.model.mapper.TTagMapper;
import com.have.blog.model.models.TBlog;
import com.have.blog.model.models.TBlogExample;
import com.have.blog.model.models.TTag;
import com.have.blog.model.models.TTagExample;
import com.have.blog.utils.MyStringUtils;
import com.have.blog.utils.ResultUtils;
import com.have.blog.xo.constant.MessageConstant;
import com.have.blog.xo.constant.SysConstant;
import com.have.blog.xo.service.admin.AdminBlogTagSevice;
import com.have.blog.xo.vo.AdminBlogTagVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;

@Service
@SuppressWarnings("all")
public class AdminBlogTagServiceImpl implements AdminBlogTagSevice {
    @Autowired
    private TTagMapper tagMapper;
    @Autowired
    private RedisService redisService;
    @Autowired
    private TBlogMapper blogMapper;

    @Override
    public String getList(AdminBlogTagVo tagVO) {
        PageHelper.startPage(tagVO.getCurrentPage(), tagVO.getPageSize());
        TTagExample example = new TTagExample();
        TTagExample.Criteria criteria = example.createCriteria();
        if (!StringUtils.isEmpty(tagVO.getKeyword()) && !StringUtils.isEmpty(tagVO.getKeyword().trim())) {
            criteria.andContentLike(tagVO.getKeyword());
        }
        criteria.andStatusEqualTo(BlogStatus.ENABLE.getStatus());
        if(!StringUtils.isEmpty(tagVO.getOrderByAscColumn())) {
            // 将驼峰转换成下划线
            String column = MyStringUtils.underLine(new StringBuffer(tagVO.getOrderByAscColumn())).toString();
            example.setOrderByClause(column + " asc");
        } else if(!StringUtils.isEmpty(tagVO.getOrderByDescColumn())) {
            // 将驼峰转换成下划线
            String column = MyStringUtils.underLine(new StringBuffer(tagVO.getOrderByDescColumn())).toString();
            example.setOrderByClause(column + " desc");
        } else {
            example.setOrderByClause("sort desc");
        }
        List<TTag> tagList = tagMapper.selectByExample(example);
        return ResultUtils.successWithData(CommonPage.restPage(tagList));
    }


    @Override
    public String addTag(AdminBlogTagVo tagVO) {
        String content = tagVO.getContent();
        TTagExample example = new TTagExample();
        example.createCriteria()
                .andStatusEqualTo(BlogStatus.ENABLE.getStatus())
                .andContentEqualTo(content);
        List<TTag> tagList = tagMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(tagList)) {
            return ResultUtils.errorWithMessage(MessageConstant.ENTITY_EXIST);
        }
        TTag tTag = new TTag();
        tTag.setUid(MyStringUtils.getUUID());
        tTag.setContent(tagVO.getContent());
        tTag.setSort(tagVO.getSort());
        tTag.setStatus(BlogStatus.ENABLE.getStatus());
        tTag.setClickCount(0);
        tTag.setCreateTime(new Date());
        tTag.setUpdateTime(new Date());
        tagMapper.insert(tTag);
        deleteRedisBlogTagList();
        return ResultUtils.successWithMessage(MessageConstant.INSERT_SUCCESS);
    }

    @Override
    public String editTag(AdminBlogTagVo tagVO) {
        TTag tTag = tagMapper.selectByPrimaryKey(tagVO.getUid());
        if (tTag == null) {
            return ResultUtils.errorWithMessage(MessageConstant.PARAM_INCORRECT);
        }
        tTag.setContent(tagVO.getContent());
        tTag.setSort(tagVO.getSort());
        tTag.setUpdateTime(new Date());
        tagMapper.updateByPrimaryKey(tTag);
        deleteRedisBlogTagList();
        return ResultUtils.successWithMessage(MessageConstant.UPDATE_SUCCESS);
    }

    @Override
    public String deleteBatchTag(List<AdminBlogTagVo> tagVoList) {
        if (CollectionUtils.isEmpty(tagVoList)) {
            return ResultUtils.errorWithMessage(MessageConstant.PARAM_INCORRECT);
        }
        List<String> uids = new ArrayList<>();
        tagVoList.forEach(item -> {
            uids.add(item.getUid());
        });
        TTagExample example = new TTagExample();
        example.createCriteria()
                .andUidIn(uids);
        TTag tTag = new TTag();
        tTag.setStatus(BlogStatus.DISABLE.getStatus());
        tagMapper.updateByExampleSelective(tTag, example);
        deleteRedisBlogTagList();
        return ResultUtils.successWithMessage(MessageConstant.DELETE_SUCCESS);
    }


    @Override
    public String stickTag(AdminBlogTagVo tagVO) {
        PageHelper.startPage(1, 1);
        TTag tTag = tagMapper.selectByPrimaryKey(tagVO.getUid());

        TTagExample example = new TTagExample();
        example.createCriteria()
                .andStatusEqualTo(BlogStatus.ENABLE.getStatus());
        example.setOrderByClause("sort desc");
        List<TTag> tagList = tagMapper.selectByExample(example);
        if (StringUtils.isEmpty(tagList)) {
            return ResultUtils.successWithMessage(MessageConstant.OPERATION_SUCCESS);
        }
        TTag maxTag = tagList.get(0);
        tTag.setSort(maxTag.getSort() + 1);
        tTag.setUpdateTime(new Date());
        tagMapper.updateByPrimaryKey(tTag);
        deleteRedisBlogTagList();
        return ResultUtils.successWithMessage(MessageConstant.OPERATION_SUCCESS);
    }

    @Override
    public String tagSortByClickCount() {
        TTagExample example = new TTagExample();
        example.createCriteria()
                .andStatusEqualTo(BlogStatus.ENABLE.getStatus());
        example.setOrderByClause("click_count desc");
        List<TTag> tagList = tagMapper.selectByExample(example);
        // TODO 批量更新操作
        tagList.forEach(item -> {
            item.setSort(item.getClickCount());
            item.setUpdateTime(new Date());
            tagMapper.updateByPrimaryKey(item);
        });
        deleteRedisBlogTagList();
        return ResultUtils.successWithMessage(MessageConstant.OPERATION_SUCCESS);
    }

    @Override
    public String tagSortByCite() {
        // 定义Map   key：tagUid,  value: 引用量
        Map<String, Integer> map = new HashMap<>();
        TTagExample example = new TTagExample();
        example.createCriteria()
                .andStatusEqualTo(BlogStatus.ENABLE.getStatus());
        List<TTag> tagList = tagMapper.selectByExample(example);
        // 初始化所有标签的引用量
        tagList.forEach(item -> {
            map.put(item.getUid(), 0);
        });

        TBlogExample blogExample = new TBlogExample();
        blogExample.createCriteria()
                .andStatusEqualTo(BlogStatus.ENABLE.getStatus())
                .andIsPublishEqualTo(BlogPublishStatus.PUBLISH.getStatus());

        // 过滤content字段
        List<TBlog> blogList = blogMapper.selectByExample(blogExample);

        blogList.forEach(item -> {
            String tagUids = item.getTagUid();
            List<String> tagUidList = MyStringUtils.changeStringToStringList(tagUids, SysConstant.FILE_SEGMENTATION);
            for (String tagUid : tagUidList) {
                if (map.get(tagUid) != null) {
                    Integer count = map.get(tagUid) + 1;
                    map.put(tagUid, count);
                } else {
                    map.put(tagUid, 0);
                }
            }
        });

        // TODO 批量更新
        tagList.forEach(item -> {
            item.setSort(map.get(item.getUid()));
            item.setUpdateTime(new Date());
            tagMapper.updateByPrimaryKey(item);
        });

        // 删除Redis中的BLOG_TAG
        deleteRedisBlogTagList();
        return ResultUtils.successWithMessage(MessageConstant.OPERATION_SUCCESS);
    }

    /**
     * TODO 删除redis中的友链连接
     */
    private void deleteRedisBlogTagList() {
    }

}
